# 6.7 Shared Method Extension

# 1. Basic Usage

The Enjoy Template Engine allows you to effortlessly use any public method from any Java class directly. The Java class being used doesn't need to implement any interfaces or inherit from any abstract classes, making it completely decoupled. The following code uses the com.jfinal.kit.StrKit class from JFinal as an example:

public void configEngine(Engine me) {
   me.addSharedMethod(new com.jfinal.kit.StrKit());
}
1
2
3

The code above adds all the public methods from the StrKit class as shared methods. Once added, they can be used directly in the template. Here is a code example:

#if(isBlank(nickName))
   ...
#end
 
#if(notBlank(title))
   ...
#end
1
2
3
4
5
6
7

In the example above, the methods isBlank and notBlank are from the StrKit class. This extension method is simple, convenient, and decoupled.

# 2. Default Shared Method Configuration Extension

The Enjoy Template Engine has a default configuration that adds com.jfinal.template.ext.sharedmethod.SharedMethodLib as a Shared Method. Therefore, the methods inside it can be used directly without any additional configuration. The library includes isEmpty(...) and notEmpty(...) methods.

The isEmpty(...) method is used to determine whether the number of elements in Collection, Map, Array, Iterator, and Iterable type objects is zero. The rules are as follows:

  • Returns true for null
  • For List, Set, and any class that inherits from Collection, returns isEmpty()
  • For Map, returns isEmpty()
  • For arrays, returns length == 0
  • For Iterator, returns !hasNext()
  • For Iterable, returns !iterator().hasNext()

Here is a code example:

#if ( isEmpty(list) )
    The number of elements in the list is 0
#end
 
#if ( notEmpty(map) )
    The number of elements in the map is greater than 0
#end
1
2
3
4
5
6
7

As shown above, isEmpty(list) checks if the number of elements in the list is greater than zero. The functionality of notEmpty(...) is exactly the opposite of isEmpty(...), equivalent to !isEmpty(...).

Last Updated: 9/22/2023, 4:50:57 AM